package br.com.foxinline.servico;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author laverson
 */
public class ServicoGenerico<T> {

    @PersistenceContext
    private EntityManager entityManager;
    private Class<T> entity;

    public ServicoGenerico(Class<T> entity) {
        this.entity = entity;
    }

    public void salvar(T entity) {
        entityManager.persist(entity);
    }

    public void deletar(T entity) {
        T entityToBeRemoved = entityManager.merge(entity);
        entityManager.remove(entityToBeRemoved);
    }

    public void atualizar(T entity) {
        entityManager.merge(entity);
        entityManager.flush();
    }

    public T pesquisar(Long entityID) {
        return entityManager.find(entity, entityID);
    }

    public List<T> pesquisarTodos() {
        return entityManager.createQuery("select e from " + entity.getSimpleName() + " e").getResultList();
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public Long quantidadeRegistros() {
        Long result = (Long) entityManager.createQuery("select count(e) from " + entity.getSimpleName() + " e").getSingleResult();

        return result != null ? result : 0;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public List<T> pesquisar(T t, int first, int pageSize) {
        String sql = "select e from " + entity.getSimpleName() + " e";

        Query query = entityManager.createQuery(sql).setFirstResult(first).setMaxResults(pageSize);

        return query.getResultList();
    }
}
